<template>
  <div style="height: 100%; height: 100%; position: relative" ref="D3_dom">
    <div  id="box_people"  class="box_people">
      <div class="box_people_title">
        <p>{{ tcData.roomName }}</p>
        <p style="color: #fff;margin-left: auto;" @click="handleGoDP3()">项目轨迹</p>
      </div>
      <div class="box_people_content">
        <ul>
          <li>
            <span>项目信息：</span>
            <span>{{ tcData.projectName }}</span>
          </li>
          <li>
            <span>应到人数：</span>
            <span>专家{{tcData.ydrs}}人</span>
          </li>
          <li>
            <span>实到人数：</span>
            <span>专家{{tcData.sdrs}}人</span>
          </li>
        </ul>
      </div>
      <div class="box_people_list">
        <div v-if="tcData.personVOS.length > 2" @click="handleGoLeft(true)"><i class="el-icon-arrow-left"></i></div>
        <ul class="flex" ref="flex">
          <li v-for="(item, index) in tcData.personVOS" :key="index" @click="handleClickItem(item)"> 
            <!-- item.pic -->
            <div class="divimg"> <TouimgComponent :src="item.pic" /></div>
            <div class="divMsg">
              <p>{{  peopList[item.personType] }}</p>
              <p>{{ item.personName }}</p>
            </div>
          </li>
        </ul>
        <div v-if="tcData.personVOS.length > 2" @click="handleGoLeft()"><i class="el-icon-arrow-right"></i></div>
      </div>
    </div>
    <div class="button_box">
    </div>
  </div>
</template>
  
  <script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import TouimgComponent from "@/views/witness/components/Object3D/touimgComponent.vue"
import { CSS2DRenderer,CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.js"
import model,{mesh} from "@/views/witness/components/Object3D/canvas/model.js"; //模型对象
import  {createText} from '@/views/witness/components/Object3D/canvas/createText.js'
import { peopList} from "@/views/witness/components/Object3D/canvas/const.js"
 import dataJson  from '@/views/witness/components/Object3D/canvas/room.json'
export default {
  components:{
    TouimgComponent
  },
  props:{
    onEmit:{
      type:Function,
      default:(val)=>val
    }
  },
  data() {
    return {
      // touxianglist:[require('@/assets/imgs/dp/专家.png'),require('@/assets/imgs/dp/专家2.png'),require('@/assets/imgs/dp/专家3.png')],
      peopList,
      tcData:{
          personId:undefined,
          projectId:'',
          roomName:'',
          projectName:'',
          sdrs:'',
          ydrs:'',
          bidId:'',
          time:'',
          personVOS:[]
        },
      D3data: {},
      textarea: ""
      // touimg:'./'
    };
  },
  methods: {
    // 根据泡泡选择项目
    getObject3DPaoPao(val){
      if(!val) {
         document.querySelector('#box_people').style.display = "none"
        return
      } 
      const PPData =  mesh.getObjectByName('全部泡泡')
      const changdi = PPData.getObjectByName(val)
      console.log('PPData',PPData);
      
      console.log('changdi',changdi);
      
    
       // 获取模型在屏幕上的坐标
      const getScreenPosition = (object)  => {
        const width = this.$refs["D3_dom"].offsetWidth;
        const height = this.$refs["D3_dom"].offsetHeight;
        const vector = new THREE.Vector3();
        // 将模型的世界坐标转换为标准化设备坐标（NDC）
        vector.setFromMatrixPosition(object.matrixWorld);
        vector.project(this.D3data.camera);
        // 将 NDC 坐标转换为屏幕坐标
        const screenX = Math.round((vector.x + 1) * width / 2);
        const screenY = Math.round((1 - vector.y) * height / 2);
        return { x: screenX, y: screenY };
      }
      const changdiPostion = getScreenPosition(changdi)
            document.querySelector('#box_people').style.top= changdiPostion.y +'px'
            document.querySelector('#box_people').style.left= changdiPostion.x + 20 +'px'
            document.querySelector('#box_people').style.display = "block"
            this.tcData = changdi.Message
    },
    // 跳转人员轨迹
    handleClickItem(item){
      this.$set(this.tcData,'personId',item.personId)
      this.handleGoDP3()
    },
    // 跳转项目轨迹
    handleGoDP3(){
      // this.$router.push({path:'/DP3',query:this.tcData})
    },
    // 设置房间名称
    setRoomName(){
      const data = [...dataJson['十楼'],...dataJson['十二楼']]
      const group = new THREE.Group()
      const groupPP = new THREE.Group()
      group.name = '全部房间'
      groupPP.name =  '全部泡泡'
      mesh.add(group);
      mesh.add(groupPP)
      for(const i of data){
     
        const name = i.name
        if(i.x == '0') continue 
        // if (!name) return
        const textRoomName = createText( name,10)
        textRoomName.position.set(i.x,i.y,0)
        group.add(textRoomName)
      }
      
        //   // 处理房间
        //   const prambox = model.children[0] // 场地模型
        // const arr = louceng_JSON['12层'].map(item=>{
        //   item.roomName = item.name.split('-')[1] || item.name.split('-')[0]
        //   return { ...item,}
        // })
        // for (const i in arr) {
        //   const text =  createText(arr[i].roomName,6)
        //   text.position.set(Number(arr[i].x), arr[i].y,0)
        //   prambox.add( text );
        // }
   
        

    },
    // 创建被占用场地
    threeSetCangdi(data){
      const texLoader = new THREE.TextureLoader();
      const bg_png = require("@/views/witness/components/Object3D/canvas/房间选中icon@2x.png")
      const bg_png_yellow = require("@/views/witness/components/Object3D/canvas/kbroom.png")
      const material = new THREE.MeshLambertMaterial({
              map: texLoader.load(bg_png),//map表示材质的颜色贴图属性
              transparent:true,//开启透明，这样png贴图的透明部分不显示
              // side:THREE.DoubleSide,
          });
      const material_yellow = new THREE.MeshLambertMaterial({
              map: texLoader.load(bg_png_yellow),//map表示材质的颜色贴图属性
              transparent:true,//开启透明，这样png贴图的透明部分不显示
              // side:THREE.DoubleSide,
          });
     const geometry = new THREE.PlaneGeometry( 55, 72 );
     const PPData =  mesh.getObjectByName('全部泡泡')
      for(const i in  PPData.children){
       const index =  data.findIndex(x=>x.uwbAreaId === PPData.children[i]?.name)
        if(index >= 0){
          PPData.children[i].Message =  data[index]
        }else{
          PPData.remove(PPData[i])
        }
      }
      for(const i in data){
      
        const index = PPData.children.findIndex(x=>x.name === data[i].uwbAreaId)
        if(index < 0 ){
          const {type,uwbAreaId,sdrs,x,y} = data[i]
          if(type === 'pb'){
            const plane = new THREE.Mesh( geometry, material );
            plane.name = uwbAreaId
            plane.isPP = true
            // const RoomName = data[i].roomName.split('-')[1] // 房间名称
            // plane.roomName = RoomName
            plane.Message = data[i]
            plane.position.set(x, Number(y) + 40,0)
            const text = createText(sdrs,20)
            text.position.set(0,8,0) // 加入文字
            // const textRoomName = createText(RoomName,15)
            // textRoomName.position.set(0,-60,0)
            plane.add(text)
            // plane.add(textRoomName)
            PPData.add( plane );
          }
          if(type === 'kb'){
            const geometry = new THREE.PlaneGeometry( 30, 20 );
            const plane = new THREE.Mesh( geometry, material_yellow );
            plane.name = uwbAreaId
            plane.isPP = true
            plane.Message = data[i]
            plane.position.set(x, Number(y) + 15,0)
            PPData.add( plane );
          }
        }
      }
    },
    // 删除泡泡
    handleClearBubble(){
      mesh.children
      prambox.remove(bubble)
    },

    handleGoLeft(flg) {
      this.$refs["flex"].scrollBy({
        top: 0,
        left: !flg ? 90 : -90,
        behavior: "smooth"
      });
    },
    handleClear() {
      this.D3data.scene.traverse(function (obj) {
        if (obj.isMesh) {
          //判断是否是网格模型
          obj.material.color.set(new THREE.Color("#fff"));
        }
      });
    },
    handleSelect(name) {
      // 0x00FFFFFF
      this.D3data.scene.getObjectByName(name).material.color.set(new THREE.Color("#CD5C5C"));
    },
    initDiv() {
      // const width = window.innerWidth;
      // const height = window.innerHeight;
      // 获取dom节点
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      //场景
      const scene = new THREE.Scene();
      // scene.background = new THREE.Color('#7b7e80');
      scene.background = null;
      scene.add(model);
      // 添加一个辅助网格地面 1468 × 400
      // const gridHelper = new THREE.GridHelper(1468, 400, 0x004444, 0x004444);
      // scene.add(gridHelper);
      //光源设置
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      directionalLight.position.set(100, 60, 50);
      scene.add(directionalLight);
      const ambient = new THREE.AmbientLight(0xffffff, 2);
      scene.add(ambient);

      //渲染器和相机
      const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
      camera.position.set(0, 0, 1800);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height);
      renderer.setClearAlpha(0);
      renderer.setPixelRatio(window.devicePixelRatio); //防止输出模糊
      renderer.outputEncoding = THREE.sRGBEncoding;
      this.$refs["D3_dom"]?.appendChild(renderer.domElement);
      // document.body.appendChild(renderer.domElement);

      // 插入css2渲染器
      const css2Renderer = new CSS2DRenderer();
      css2Renderer.setSize(width, height);
      css2Renderer.domElement.style.position = 'absolute';
      css2Renderer.domElement.style.top = '0px';
      // css2Renderer.domElement.style.display='none';
      css2Renderer.domElement.style.pointerEvents = 'none' ;
      this.$refs["D3_dom"]?.appendChild(css2Renderer.domElement);
       // 坐标拾取 // 显示房间信息
       renderer.domElement.addEventListener('click',(event)=>{
        // console.log('event',event);
      const px = event.offsetX;
      const py = event.offsetY;
      // 屏幕坐标px,py 转WebGL标准设备坐标x,y
      // width ,height 画布宽高度
      const x = (px/width) * 2 - 1;
      const y = - (py/height) * 2 + 1;
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(new THREE.Vector2(x,y),camera)
      const intersects = raycaster.intersectObjects(model.children[0].children)
      if(intersects.length > 0 ){
        const selectedObject = intersects[0].object;
          // console.log('selectedObject',selectedObject);
        if(!selectedObject.isPP) return
        console.log('selectedObject',selectedObject);
        
       
        // console.log('event',event.offsetX,event.offsetY)
        document.querySelector('#box_people').style.top= event.offsetY  +'px'
        document.querySelector('#box_people').style.left= event.offsetX + 20 +'px'
        // outlinePass.selectedObjects = [intersects[0].object];
        // 选中模型的第一个模型，设置为红色
        // console.log('selectedObject.message',selectedObject.mssage);
        this.tcData = selectedObject.Message
        // 通知父组件
        this.onEmit(this.tcData)
        this.getObject3DPaoPao(this.tcData.uwbAreaId)
        //  document.querySelector('#box_people').style.display = "block"
      }else{
        document.getElementById('box_people').style.display = "none"
      }
        
       })
      // 渲染循环

      const controls = new OrbitControls(camera, renderer.domElement);

      // 缩放范围
      // controls.target.set(700, 200, 0); //与lookAt参数保持一致
      // controls.update(); //update()函数内会执行camera.lookAt(controls.target)
      controls.enableRotate = false; // 禁止旋转
      // controls.enableZoom = false; //禁止缩放
      // //相机位置与观察目标点最小值
      controls.minDistance = 1000;
      // //相机位置与观察目标点最大值
      controls.maxDistance = 2000;
      // controls.maxTargetRadius = 400

      controls.mouseButtons = {
          //左键平移
          LEFT: THREE.MOUSE.PAN,
          //滚轮滑动
          MIDDLE: THREE.MOUSE.DOLLY,
          //右键旋转
          RIGHT: THREE.MOUSE.ROTATE,
      };

      // 用不到
      // controls.minZoom = -1;
      // controls.maxZoom = 2;
      // controls.update();
      // controls.minTargetRadius  =
      // controls.touches = {
      //                         ONE: THREE.TOUCH.DOLLY_PAN ,
      //                         TWO: THREE.TOUCH.ROTATE,
      //                     }
      // controls.update();
      // 画布跟随窗口变化
      return {
        scene,
        // controls,
        css2Renderer,
        renderer,
        camera
      };
    },
    // 渲染循环
    animationFrameRender(){
      this.D3data.renderer.render(this.D3data.scene, this.D3data.camera);
      this.D3data.css2Renderer.render(this.D3data.scene, this.D3data.camera);
      requestAnimationFrame(this.animationFrameRender);
    }
  },
  mounted() {
   
    this.D3data = this.initDiv();
    this.animationFrameRender()
    window.onresize = () => {
      setTimeout(() => {
        const width = this.$refs["D3_dom"].offsetWidth;
        const height = this.$refs["D3_dom"].offsetHeight;
        // console.log("width", width);
        // console.log("height", height);
        
        this.D3data.renderer.setSize(width, height);
        this.D3data.css2Renderer.setSize(width, height);
        this.D3data.camera.aspect = width / height;
        this.D3data.camera.updateProjectionMatrix();
      }, 300);
    };
    this.setRoomName()
  }
};
</script>
  
  <style scoped lang="scss">
.button_box {
  position: absolute;
  top: 10px;
  left: 10px;
}
.box_people {
  cursor: default;
  position: absolute;
  display: none;
  // top: 130px;
  // right: 100px;
  width: 424px;
  height: 330px;
  padding: 4px 6px;
  background-image: url("../../components/Object3D/canvas/弹窗底@2x.png");
  background-size: 100% 100%;
  // background-attachment:fixed;
  .box_people_title {
    display: flex;
    height: 40px;
    line-height: 38px;
  }
  .box_people_content {
    li {
      height: 28px;
      font-size: 14px;
      &:first-child {
        height: 50px;
      }
    }
  }
  .box_people_list {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  .flex {
    display: flex;
    width: 424px;
    overflow-y: hidden;
    overflow-x: scroll;
    &::-webkit-scrollbar {
      height: 0;
    }
    // border: 1px solid red;
    ul {
    }
    li {
      position: relative;
      width: 130px;
      height: 170px;
      // components/canvas/头像背景@2x.png
      background-image: url("../../components/Object3D/canvas/头像背景@2x.png");
      background-size: 100% 100%;
      .divMsg {
        width: 130px;
        margin-top: -10px;
        font-size: 14px;
        text-align: center;
      }
      .divimg {
        margin-top: 6px;
        margin-left: 25px;
        width: 80px;
        height: 120px;
        // border: 1px solid red;
      }
      .shape {
        margin-top: 30px;
        margin-left: 32px;
        width: 38px;
        height: 0;
        border: 24px solid transparent;
        border-top-width: 0px;
        border-bottom: 40px solid #36d792;
        position: relative;
        transform: rotate(29deg);
      }
      .shape::after {
        content: "";
        position: absolute;
        width: 38px;
        height: 0;
        border: 24px solid transparent;
        border-bottom-width: 0px;
        border-top: 40px solid #36d792;
        left: -24px;
        top: 40px;
      }
    }
  }
}
img.no-drag {
  pointer-events: none;
  user-select: none;
}
</style>
  